package com.haois.mp.database.module.person.service;

import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import cn.zhouyafeng.itchat4j.beans.BaseMsg;
import cn.zhouyafeng.itchat4j.beans.RecommendInfo;
import cn.zhouyafeng.itchat4j.face.IMsgHandlerFace;
import cn.zhouyafeng.itchat4j.utils.enums.MsgTypeEnum;
import cn.zhouyafeng.itchat4j.utils.tools.DownloadTools;
import com.haois.mp.database.module.sdk.api.ItpkService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * 简单示例程序，收到文本信息自动回复原信息，收到图片、语音、小视频后根据路径自动保存
 *
 * @author https://github.com/yaphone
 * @version 1.0
 * @date 创建时间：2017年4月25日 上午12:18:09
 */
public class SimpleDemo implements IMsgHandlerFace {
    static Set<String> robots = new HashSet<>();

    Logger logger = LoggerFactory.getLogger(SimpleDemo.class);

    private String materialPath;

    public SimpleDemo(String materialPath) {
        this.materialPath = materialPath;
    }

    @Override
    public String textMsgHandle(BaseMsg msg) {
        // String docFilePath = "D:/itchat4j/pic/1.jpg"; // 这里是需要发送的文件的路径
        if (!msg.isGroupMsg()) { // 群消息不处理
            // String userId = msg.getString("FromUserName");
            // MessageTools.sendFileMsgByUserId(userId, docFilePath); // 发送文件
            // MessageTools.sendPicMsgByUserId(userId, docFilePath);
            // 发送文本消息，也可调用MessageTools.sendFileMsgByUserId(userId,text);
            String text = msg.getText();
            logger.info("user: {}", text);
            if (text.equals("@group")) {
                WechatTools.getGroupList().forEach(j -> logger.info(""));
            } else if (text.equals("@user")) {
                WechatTools.getContactList().forEach(j -> logger.info(""));
            } else if (text.equals("@logout")) {
                WechatTools.logout();
            } else if (text.equals("@rename")) {
                WechatTools.remarkNameByNickName("hao of well", "Hello");
            } else if (text.contains("@robot")) {
                robots.add(msg.getFromUserName());
                return "start robot success\n if you want to exit\n please send @exit";
            } else if (text.contains("@exit")) {
                robots.remove(msg.getFromUserName());
                return "end robot success\n if you want to re use\n please send @robot";
            } else if (robots.contains(msg.getFromUserName())) {
                return ItpkService.question(text.replace("@", ""));
            }
        } else {
            logger.info("group: {}", msg.getText());
        }
        return null;
    }

    @Override
    public String picMsgHandle(BaseMsg msg) {
        String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        // 这里使用收到图片的时间作为文件名
        String picPath = materialPath + "/pic" + File.separator + fileName + ".jpg";
        // 调用此方法来保存图片
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.PIC.getType(), picPath);
        // 保存图片的路径
        logger.info("图片已保存：{}", picPath);
        return msg.isGroupMsg() ? null : "picture is save success";
    }

    @Override
    public String voiceMsgHandle(BaseMsg msg) {
        String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String voicePath = materialPath + "/voice" + File.separator + fileName + ".mp3";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.VOICE.getType(), voicePath);
        logger.info("音频已保存：{}", voicePath);
        return msg.isGroupMsg() ? null : "voice is save success";
    }

    @Override
    public String viedoMsgHandle(BaseMsg msg) {
        String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String videoPath = materialPath + "/video" + File.separator + fileName + ".mp4";
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.VIEDO.getType(), videoPath);
        logger.info("视频已保存：{}", videoPath);
        return msg.isGroupMsg() ? null : "video is save success";
    }

    @Override
    public String nameCardMsgHandle(BaseMsg msg) {
        logger.info("visiting card is receive");
        return "visiting card is receive";
    }

    @Override
    public void sysMsgHandle(BaseMsg msg) {
        // 收到系统消息
        String text = msg.getContent();
        logger.info("收到系统消息：{}", text);
    }

    @Override
    public String verifyAddFriendMsgHandle(BaseMsg msg) {
        MessageTools.addFriend(msg, true);
        // 同意好友请求，false为不接受好友请求
        RecommendInfo recommendInfo = msg.getRecommendInfo();
        String nickName = recommendInfo.getNickName();
        String province = recommendInfo.getProvince();
        String city = recommendInfo.getCity();
        String from = StringUtils.isBlank(province + city) ? "earth" : province + city;

        StringBuffer text = new StringBuffer("hello, from " + from + "'s " + nickName + ", nice to meet you !");
        text.append("\nif you want to using robot, please send @robot to me");
        logger.info("收到好友请求：{}", text);
        return msg.isGroupMsg() ? null : text.toString();
    }

    @Override
    public String mediaMsgHandle(BaseMsg msg) {
        String fileName = msg.getFileName();
        String filePath = materialPath + "/file" + File.separator + fileName;
        // 这里是需要保存收到的文件路径，文件可以是任何格式如PDF，WORD，EXCEL等。
        DownloadTools.getDownloadFn(msg, MsgTypeEnum.MEDIA.getType(), filePath);
        logger.info("多媒体已保存：{}", filePath);
        return null;
    }

}
